package com.example.wordlistdemo;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ScaleXSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.text.HtmlCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.example.wordlistdemo.api.WordApiRequest;
import com.example.wordlistdemo.entity.BlngSentsPart;
import com.example.wordlistdemo.entity.EcEntiity;
import com.example.wordlistdemo.entity.MediaPartEntity;
import com.example.wordlistdemo.entity.WordDetailEntity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WordDetailActivity extends AppCompatActivity {
    List<Map<String,String>> partList = new ArrayList<>();
    List<MediaPartEntity.Sent> sentList = new ArrayList<>();

    List<BlngSentsPart.SentencePair> sentencePairs = new ArrayList<>();
    List<String> wfList = new ArrayList<>();
    private MediaPlayer mediaPlayer;

    String phUs = "";
    String phUk = "";
    String phUkMp3 = "";
    String phUsMp3 = "";

    String tagsText = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail2);
        mediaPlayer = new MediaPlayer();

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("详情");


        // 实例化WordApiRequest
        WordApiRequest wordApiRequest = new WordApiRequest();

        // 要查询的单词
        String wordToSearch = "scope";
        Intent intent = getIntent();
        if (intent.hasExtra("english")) {
            // 获取英文参数
            wordToSearch = intent.getStringExtra("english");
        }
        TextView wordTitle = findViewById(R.id.wordTextView);
        wordTitle.setText(wordToSearch);

        // 发起单词请求
        wordApiRequest.getWordMeaning(wordToSearch, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理请求失败的情况
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                // 处理请求成功的情况
                if (response.isSuccessful()) {
                    // 将结果传递给回调
                    String responseBody = response.body().string();
                    System.out.println(responseBody);
                    WordDetailEntity wordDetailEntity = JSON.parseObject(responseBody, WordDetailEntity.class);
                    EcEntiity ecEntiity = wordDetailEntity.getEc();


                    EcEntiity.Word ecWord =  ecEntiity.getWordList().get(0);


                    List<EcEntiity.WordForm> ecWfs = ecWord.getWfs();
                    if(ecWfs == null || ecWfs.size()==0){
                        ecWfs = new ArrayList<>();
                    }
                    for (EcEntiity.WordForm ecWf : ecWfs) {
                        EcEntiity.WordFormValue wf = ecWf.getWf();
                        String name = wf.getName();
                        String value = wf.getValue();
                        wfList.add(name+":"+value);
                    }


                    //考试级别标签
                    List<String> examType = ecEntiity.getExamType();
                    tagsText = examType.stream().collect(Collectors.joining(" / "));

                    //音标
                    phUs = ecWord.getUsPhone();
                    phUk = ecWord.getUkPhone();
                    String speechUri = "https://dict.youdao.com/dictvoice?audio=";
                    phUkMp3 = speechUri+ecWord.getUkSpeech();
                    phUsMp3 = speechUri+ecWord.getUsSpeech();
                    //中文翻译
                    List<EcEntiity.Translation> trs = ecWord.getTrs();
                    for (EcEntiity.Translation tr : trs) {
                        String zhName = tr.getTr().get(0).getL().getI().get(0);
                        String[] zhNameStrArray = zhName.split("\\.");
                        Map<String,String> map = new HashMap<>(0);
                        map.put("part","");
                        map.put("means",zhName);
                        partList.add(map);
                    }

                    //例句
                    //sentList = wordDetailEntity.getMediaPart().getSentList();

                    //双语
                    sentencePairs = wordDetailEntity.getBlngSentsPart().getPairList();

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            addTags();
                            addMeans();
                            addPhInfo();
                            addWfs();
                            addSentInfo();
                        }
                    });

                } else {
                    // 请求失败
                    System.out.printf("fail");
                }
            }
        });

    }

    private void addTags(){
        TextView tagsTextView = findViewById(R.id.tagsTextView);
        tagsTextView.setText(tagsText);
    }

    private void addPhInfo(){
        TextView phUkView = findViewById(R.id.ukSymbolTextView);
        TextView phUsView = findViewById(R.id.usSymbolTextView);

        phUkView.setText(phUk);
        phUsView.setText(phUs);

        // 获取音标ImageView
        ImageView ukSymbolImageView = findViewById(R.id.ukSymbolImage);
        ImageView usSymbolImageView = findViewById(R.id.usSymbolImage);

        // 设置点击事件监听器
        ukSymbolImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playAudio(phUkMp3);
            }
        });

        usSymbolImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playAudio(phUsMp3);
            }
        });
    }
    private void addWfs(){
        LinearLayout parentLayout = findViewById(R.id.wfsDetailLayout);
        for (String s : wfList) {
            addLinearLayout(parentLayout,"",s);
        }
    }
    private void addMeans(){
        LinearLayout parentLayout = findViewById(R.id.definitionLayout);
        for (Map<String, String> part : partList) {
            String means = part.get("means");
            addLinearLayout(parentLayout,part.get("part"),means);
        }
    }

    private void addSentInfo(){
        LinearLayout parentLayout = findViewById(R.id.sentDetailLayout);
        for (BlngSentsPart.SentencePair sent : sentencePairs) {
            String chn = sent.getSentenceTranslation();
            String eng = sent.getSentenceEng();
            addMediaLinearLayout(parentLayout,chn,eng);
        }
    }

    private void addMediaLinearLayout(LinearLayout parentLayout, String chn, String eng) {

        LinearLayout linearLayoutB = new LinearLayout(this);
        linearLayoutB.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        linearLayoutB.setOrientation(LinearLayout.VERTICAL);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        float textSizeInSp = 16;
        Typeface customTypeface = Typeface.createFromAsset(getAssets(), "gilroy.otf");
        // 添加英文例句
        TextView engView = new TextView(this);
        engView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeInSp);
        engView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        // 使用 SpannableString 设置字体
        eng = eng.replace("<b>","<font color=\"#FF0000\">").replace("</b>","</font>");
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(HtmlCompat.fromHtml(eng, HtmlCompat.FROM_HTML_MODE_LEGACY));
        setSpannableStringFont(spannableStringBuilder, customTypeface);
        engView.setText(spannableStringBuilder);

        // 添加中文翻译行
        TextView chnView = new TextView(this);
        chnView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeInSp);
        chnView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        // 使用 SpannableString 设置字体
        SpannableStringBuilder chnSpannableStringBuilder = new SpannableStringBuilder();
        chnSpannableStringBuilder.append(HtmlCompat.fromHtml(chn, HtmlCompat.FROM_HTML_MODE_LEGACY));
        setSpannableStringFont(chnSpannableStringBuilder, customTypeface);
        chnView.setText(chnSpannableStringBuilder);

        //添加空行
        TextView nullView = new TextView(this);
        nullView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
               20));

        linearLayout.addView(engView);
        linearLayout.addView(chnView);
        linearLayout.addView(nullView);
        linearLayoutB.addView(linearLayout);

        parentLayout.addView(linearLayoutB);
    }
    private void setSpannableStringFont(SpannableStringBuilder spannableStringBuilder, Typeface typeface) {
        // 使用 StyleSpan 设置字体
        StyleSpan styleSpan = new StyleSpan(Typeface.NORMAL);

        SpannableString spannableString = new SpannableString(spannableStringBuilder);
        spannableString.setSpan(new TypefaceSpan(typeface), 0, spannableString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(styleSpan, 0, spannableString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 将设置好字体的 SpannableString 应用到原始的 SpannableStringBuilder 中
        spannableStringBuilder.clear();
        spannableStringBuilder.append(spannableString);
    }
    private void addLinearLayout(LinearLayout parentLayout, String type, String definition) {
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

        // Create and add TextView for type
        TextView typeTextView = new TextView(this);
        typeTextView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        typeTextView.setText(type);

        linearLayout.addView(typeTextView);

        // Create and add TextView for definition
        TextView definitionTextView = new TextView(this);

        float textSizeInSp = 15;

        definitionTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeInSp);


        SpannableString spannableString = new SpannableString(definition);

        // 设置字间距
        float letterSpacing = 0.1f;
        spannableString.setSpan(new ScaleXSpan(1 + letterSpacing), 0, type.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        definitionTextView.setLayoutParams(new LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1)); // Set layout_weight to 1
        definitionTextView.setText(spannableString);
        linearLayout.addView(definitionTextView);

        // Add the new LinearLayout to the parent layout
        parentLayout.addView(linearLayout);
    }

    private void playAudio(String audioUrl) {
        try {
            // 重置MediaPlayer
            mediaPlayer.reset();
            // 设置数据源
            Context appContext = getApplication();
            mediaPlayer.setDataSource(appContext, Uri.parse(audioUrl));
            // 异步准备MediaPlayer
            mediaPlayer.prepareAsync();
            // 设置准备完成监听器
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    // 开始播放
                    mediaPlayer.start();
                }

            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    // 打印错误信息
                    System.out.println("MediaPlayerError: " + what + ", Extra: " + extra);
                    return false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initEcDetail(){

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}

